/**
 * 获取URL中某参数值
 *
 * @param name 参数名
 */
export const getURLParam = (name: string): string | null => {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  const r = location.search.substr(1).match(reg)
  if (r) {
    return decodeURIComponent(r[2])
  }
  return null
}

/**
 * 隐藏字符串，至少隐藏最后一位
 *
 * @param str 需隐藏的字符串
 * @param start 不隐藏的字符数-开始
 * @param end 不隐藏的字符数-结束
 * @param symbol 隐藏后替换的字符，默认 *
 */
export const hideString = (
  str: string,
  start: number = 0,
  end: number = 0,
  symbol: string = '*'
): string => {
  if (!str) {
    return ''
  }
  let length = str.length - end - start
  if (length <= 0) {
    length = str.length - start
    end = 0
    if (length <= 0) {
      length = 1
      start = str.length - 1
    }
  }
  let middleStr = ''
  while (length > 0) {
    middleStr += symbol
    length -= 1
  }
  let reg = new RegExp('^(.{' + start + '}).*(.{' + end + '})$')
  return str.replace(reg, '$1' + middleStr + '$2')
}

/**
 * 数组转换树形结构
 *
 * @param arr 需要转换的数组
 * @param parentId 根节点 id
 * @param childKey 子节点 id 字段名
 * @param parentKey 父节点 id 字段名
 */
export const buildTree = (
  arr: Array<object>,
  parentId: string | null = null,
  childKey: string = 'id',
  parentKey: string = 'parentId'
): Array<object> => {
  interface TreeObject {
    [string: string]: any
  }

  let temp: TreeObject = {}
  let tree = []
  arr.forEach((item: TreeObject) => {
    temp[item[childKey]] = item
  })

  for (const key in temp) {
    const item = temp[key]
    if (item[parentKey] === parentId) {
      tree.push(item)
    } else {
      const parent = temp[item[parentKey]]
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(item)
      }
    }
  }

  return tree
}

/**
 * 以文件名导出默认模块
 *
 * @param r require.context
 */
export const importDefaultModuleAll = (
  r: __WebpackModuleApi.RequireContext
): any => {
  return r.keys().reduce((acc: any, path: string) => {
    const exportName = path.replace(/^\.\/(.*)\.\w+$/, '$1')
    const exportModule = r(path).default

    acc[exportName] = exportModule
    return acc
  }, {})
}
